<template>
  <div class="city-elevator-container">
    <nut-elevator
      v-if="allCitydata.length > 0"
      :index-list="formatAllCityData(allCitydata)"
      :height="elevatorContainerHeight"
      :is-sticky="true"
      @click-item="clickItem"
    >
      <template v-slot:default="slotProps">
        <nut-button shape="square" type="default" size="small" block>
          {{ slotProps.item.cityName }}
        </nut-button>
      </template>
    </nut-elevator>
  </div>
</template>
<script setup lang="ts">
import Taro, { eventCenter } from "@tarojs/taro";
import { ref, onMounted, computed } from "vue";
import { useLocationStore } from "../../store";
import { storeToRefs } from "pinia";
import * as Tools from "../../utils/tools";
import * as _ from "underscore";
const locationStore = useLocationStore();
const { allCitydata } = storeToRefs(locationStore);
const emit = defineEmits(["clickItem"]);

const elevatorContainerHeight = ref(0);
const router = Taro.useRouter();
onMounted(() => {
  eventCenter.once(router.onReady, () => {
    getElevatorContainer();
  });
});
const clickItem = (key, item) => {
  emit("clickItem", item);
};
const getElevatorContainer = () => {
  const query = Taro.createSelectorQuery()
    .select(".elevator-container")
    .boundingClientRect();
  query.selectViewport();
  query.exec(function (res) {
    if (res[0]) {
      elevatorContainerHeight.value = res[0].height;
    }
  });
};

// 【格式化】所有城市数据
const formatAllCityData = computed(() => {
  return (res) => {
    let arr: any = [];
    const obj = Tools.arrayGroupBy(res, "firstletter");
    for (const key in obj) {
      arr.push({
        title: key,
        list: obj[key],
      });
    }
    arr = _.sortBy(arr, (i) => {
      return i.title.toLowerCase();
    });
    return arr;
  };
});
</script>
<style lang="less">
.city-elevator-container {
  height: 100%;
  width: 100%;
  .nut-elevator__list__item__code {
    margin-bottom: 1rem;
  }
  .nut-elevator__list__item__name {
    display: inline-block;
    padding: 0;
    margin: 0 0 0.5rem 0.5rem;
    width: 5.5rem;
  }
}
</style>
